package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"NicePay/yclient"
	"NicePay/utils"
	"NicePay/model"
	"time"
	"net/url"
	"encoding/json"
	"NicePay/websocket"
)

var Notify = gin.HandlerFunc(func(ctx *gin.Context) {
	// 返回都是固定的
	ctx.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success"})
	// 反序列化表单数据
	f := new(NotifyForm)
	ctx.Bind(f)
	// 验证是否伪造
	yzCfg := utils.GetConfig().YouZan
	if utils.MD5hash(yzCfg.ClientId, f.Msg, yzCfg.ClientSecret) != f.Sign {
		return
	}
	// 只处理交易成功的消息
	if f.Type == _TRADE_ORDER_STATE && f.Status == _TRADE_SUCCESS {
		u, _ := url.QueryUnescape(f.Msg)
		notifyMsg := new(NotifyMsg)
		json.Unmarshal([]byte(u), notifyMsg)
		// 异步处理结果
		go updateAsync(notifyMsg.Tid, notifyMsg.PayType)
	}
})

func updateAsync(tid, payType string) {
	// 获取 QrId
	trade := yclient.Obtain().FetchQrId(tid)
	orm := utils.Orm()
	pay := new(model.Payment)
	orm.Where("qr_id = ?", trade.QrId).First(pay)
	// 未找到此条数据
	if orm.NewRecord(pay) {
		return
	}
	uinfo := new(model.UserInfo)
	orm.Where("uid = ?", pay.Uid).First(uinfo)
	pay.Status = model.Success
	pay.FinishAt = time.Now()
	pay.Tid = tid
	pay.PayType = payType
	pay.OuterTid = trade.OuterTid
	pay.TransactionTid = trade.TransactionTid
	pay.CoinBefore = uinfo.Coin
	uinfo.Coin += pay.Price
	pay.CoinAfter = uinfo.Coin
	orm.Save(pay)
	orm.Save(uinfo)
	// websocket 广播给付款成功的客户端
	websocket.TradeSuccess(pay.Uid)
}
